#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MSTK.h"

int main(int argc, char *argv[]) {
  int k, len, suff, ok;
  char mname[256], filename[256], outfilename[256];
  Mesh_ptr mesh;
    
  int verbose = 0;
  int enable_set = 0;
  int has_out_name = 0;
 /* command line parameter */
  
  if (argc == 1) {
    fprintf(stdout, "Usage: mstk2exo [option] inputfilename.mstk [-o outputfilename]\n");
    fprintf(stdout, "Option: -h for help\n");
    fprintf(stdout, "        -v output additional ExodusII file information\n");
    fprintf(stdout, "        -s enable ExodusII node set and side set ability based on geometric entity\n");
    fprintf(stdout, "        -o outputfilename sets ExodusII output file name, default is inputfilename.exo\n");
    return -1;
  }
  argc--;
  argv++;
    
  while (argc >= 1)
    {
      if (argv[0][0] == '-') {	
	switch(argv[0][1]) {
	case 'h':
	case 'H':
	  fprintf(stdout, "Usage: mstk2exo [option] inputfilename.mstk [-o outputfilename]\n");
	  fprintf(stdout, "Option: -h for help\n");
	  fprintf(stdout, "        -v output additional ExodusII file information\n");
	  fprintf(stdout, "        -s enable ExodusII node set and side set ability based on geometric entity\n");
	  fprintf(stdout, "        -o outputfilename sets ExodusII output file name, default is inputfilename.exo\n");
   	  argc -= 1;
          argv += 1;
	  return -1;
	  break;
	case 's':
	case 'S':
	  enable_set = 1;
	  argc -= 1;
	  argv += 1;
          break;
	case 'v':
	case 'V':
	  verbose = 1;
	  argc -= 1;
	  argv += 1;
	  break;
	case 'o':
	case 'O':
	  strcpy(outfilename,argv[1]);
	  has_out_name = 1;
	  argc -= 2;
	  argv += 2;
	  break;
	}
      }
      else {
	strcpy(mname,argv[0]);
	argc -= 1;
	argv += 1;
      }
    }


  fprintf(stderr,"\n");
  /* Initialize MSTK - Always do this even if it does not seem to
     matter in this version of MSTK */
  MSTK_Init();

  /* Load the mesh */
  len = strlen(mname);
  suff = 0;
  if (len > 5) {
    k = len-5;
    while (!suff && k > 1) {
      if (strncmp(&(mname[k]),".mstk",5) == 0) {
        suff = 1;
      }
      else
        k--;
    }
  }
  if (suff)
    mname[len-5] = '\0';

  strcpy(filename,mname);
  strcat(filename,".mstk");

  mesh = MESH_New(UNKNOWN_REP);
  ok = MESH_InitFromFile(mesh,filename);
  if (!ok) {
    fprintf(stderr,"Cannot open input file %s\n\n\n",filename);
    exit(-1);
  }
  fprintf(stdout, "MSTK file %s read in\n", filename);

  /* Write out a copy of the mesh */



  if (!has_out_name) {
  strcpy(outfilename,mname);
  strcat(outfilename,".exo");
  }


  MESH_ExportToEXODUSII_cubit(mesh,outfilename,enable_set,verbose);
  
  fprintf(stdout, "\nEXODUSII file %s created\n", outfilename);
  
  /* Deleting of mesh is not necessary if this the end of the program */
  MESH_Delete(mesh);

  return 1;
}
